package serialize;

import java.io.*;

/**
 * author : yeswater
 * date : 2023/7/2
 * <p>
 * 序列化相关测试
 */

public class SerializeTest {

    public static void main(String[] args) {
        // test1();
        test2();
        // test3();
    }

    /**
     * 测试序列化和反序列化
     */
    private static void test1() {
        String path = "stu.txt";
        Student student = new Student("Lucas", 20, "male");
        serialize(path, student);
        unSerialize(path);
    }

    private static void test2() {
        String path = "person.txt";
        Person person = new Person();
        Person.ATTR = "person";
        person.setName("Joe");
        System.out.println("attr : " + Person.ATTR);
        System.out.println("name : " + person.getName());
        serialize(path, person);
        Person person1 = (Person) unSerialize(path);
        System.out.println("attr : " + Person.ATTR);
        System.out.println("name : " + person1.getName());
    }

    private static void test3() {
        String path = "person.txt";
        Person person = new Person();
        person.setName("Joe");
        person.setAge("20");
        Person.ATTR = "person";
        System.out.println("attr : " + Person.ATTR);
        System.out.println("name : " + person.getName());
        System.out.println("age : " + person.getAge());
        serialize(path, person);
        Person.ATTR = "person1";
        Person person1 = (Person) unSerialize(path);
        System.out.println("attr : " + Person.ATTR);
        System.out.println("name : " + person1.getName());
        System.out.println("age : " + person1.getAge());
    }

    /**
     * 序列化
     */
    private static void serialize(String path, Object obj) {
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        try {
            fos = new FileOutputStream(path);
            oos = new ObjectOutputStream(fos);
            System.out.println("序列化");
            oos.writeObject(obj);
            oos.flush();
            oos.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反序列化
     */
    private static Object unSerialize(String path) {
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        Object object = null;
        try {
            fis = new FileInputStream(path);
            ois = new ObjectInputStream(fis);
            object = ois.readObject();
            System.out.println("反序列化");

            ois.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return object;
    }

}

